package com.daxt.controller.index;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.exception.BaseException;
import com.daxt.common.util.HttpClientUtil;
import com.daxt.model.dic.AccessoryType;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.model.dto.HttpDto;
import com.daxt.utils.BaseUtil;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.archives.ArchivesDocFileMapper;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.sys.ApplicationFunctionMapper;
import com.daxt.mapper.sys.ApplicationMapper;
import com.daxt.mapper.sys.ArchivesFondsMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.mapper.sys.DicMapper;
import com.daxt.mapper.sys.FunctionMapper;
import com.daxt.mapper.sys.RoleFunctionMapper;
import com.daxt.mapper.sys.RoleMapper;
import com.daxt.mapper.sys.SystemConfigMapper;
import com.daxt.model.dic.AuthScopeType;
import com.daxt.model.dic.MenuType;
import com.daxt.model.dto.ArchivesStatisticsDto;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.archives.vo.ArchivesFonds;
import com.daxt.model.service.base.vo.Application;
import com.daxt.model.service.base.vo.ApplicationFunction;
import com.daxt.model.service.base.vo.Dic;
import com.daxt.model.service.base.vo.Function;
import com.daxt.model.service.base.vo.Role;
import com.daxt.model.service.base.vo.RoleFunction;
import com.daxt.model.service.base.vo.SystemConfig;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "下拉列表集合")
@RestController
public class SelectListController {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private FunctionMapper functionMapper;
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private ApplicationFunctionMapper applicationFunctionMapper;
    @Autowired
    private RoleFunctionMapper roleFunctionMapper;
    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private DicMapper dicMapper;
    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private ArchivesDocFileMapper archivesDocFileMapper;

    @Value("${minio.endpoint}")
    private String endpoint;
	@Value("${minio.accessKey}")
	private String accessKey;
	@Value("${minio.secretKey}")
	private String secretKey;

    @Autowired
    private SystemConfigMapper systemConfigMapper;

    @ApiOperation(value = "获取角色", notes = "")
    @GetMapping("/select/role/all")
    public Result<List<Role>> setUserRole() {
        List<Role> list = roleMapper.selectList(null);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }

    @ApiOperation(value = "获取菜单", notes = "")
    @GetMapping("/select/function/menus/{clientType}")
    public Result<List<Function>> menus(@PathVariable("clientType") String clientType) {
        if (StringUtils.isEmpty(clientType)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
        }
        QueryWrapper<Function> queryWrapper = new QueryWrapper<Function>();
        queryWrapper.eq("clientType", clientType);
        //queryWrapper.eq("state", "1");
        queryWrapper.orderByAsc("sort");
        List<Function> list = functionMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }

    @ApiOperation(value = "获取菜单类型", notes = "")
    @GetMapping("/select/function/menuType")
    public Result<List<Map<String, String>>> menuTypes() {
        List<Map<String, String>> result = new ArrayList<>();
        MenuType[] values = MenuType.values();
        for (MenuType menuType : values) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("id", menuType.getKey());
            map.put("name", menuType.getValue());
            result.add(map);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), ResultCode.RESULT_SUCCESS.getMes(), result);
    }

    @ApiOperation(value = "获取全部系统", notes = "")
    @GetMapping("/select/application/all")
    public Result<List<Application>> all() {
        List<Application> list = applicationMapper.selectList(null);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }

    @ApiOperation(value = "获取应用授权范围类型", notes = "")
    @GetMapping("/select/application_scope")
    public Result<AuthScopeType[]> getApplicationScope() {
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, AuthScopeType.values());
    }


    @ApiOperation(value = "获取应用下的功能", notes = "")
    @GetMapping("/select/function/application/{applicationId}")
    public Result<List<ApplicationFunction>> getAppFunction(@PathVariable("applicationId") String applicationId) {
        QueryWrapper<ApplicationFunction> queryWrapper = new QueryWrapper<ApplicationFunction>();
        queryWrapper.eq("applicationId", applicationId);
        List<ApplicationFunction> list = applicationFunctionMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }


    @ApiOperation(value = "获取角色下的功能", notes = "")
    @GetMapping("/select/function/role/{roleId}")
    public Result<List<RoleFunction>> getRoleFunction(@PathVariable("roleId") String roleId) {
        QueryWrapper<RoleFunction> queryWrapper = new QueryWrapper<RoleFunction>();
        queryWrapper.eq("roleId", roleId);
        List<RoleFunction> list = roleFunctionMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }

    @ApiOperation(value = "获取全部租户", notes = "")
    @GetMapping("/select/archivesFonds/all")
    public Result<List<ArchivesFonds>> getTenant() {
        List<ArchivesFonds> list = archivesFondsMapper.selectList(null);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }


    @ApiOperation(value = "根据类型获取字典", notes = "")
    @GetMapping("/select/dic/{type}")
    public Result<List<Dic>> getDic(@PathVariable("type") String type, @RequestParam(value = "tenantId", required = false) String tenantId,
                                    @RequestParam(value = "value", required = false) String value) {
        QueryWrapper<Dic> queryWrapper = new QueryWrapper<Dic>();
        queryWrapper.eq("dicType", type);
        if (!StringUtils.isEmpty(tenantId)) {
            queryWrapper.eq("tenantId", tenantId);
        }
        if (!StringUtils.isEmpty(value)) {
            queryWrapper.like("dicType", value);
        }
        List<Dic> list = dicMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }

    @ApiOperation(value = "根据类型获取字典", notes = "")
    @GetMapping("/select/dic/all/{type}")
    public Result<List<Dic>> getAllDic(@PathVariable("type") String type, @RequestParam(value = "tenantId", required = false) String tenantId) {
        QueryWrapper<Dic> queryWrapper = new QueryWrapper<Dic>();
        queryWrapper.eq("`parentType`", type);
        if (!StringUtils.isEmpty(tenantId)) {
            queryWrapper.eq("tenantId", tenantId);
        }
        List<Dic> list = dicMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }

    @ApiOperation(value = "根据类型获取字典", notes = "")
    @GetMapping("/select/dic/list/{type}")
    public Result<List<Dic>> getDicList(@PathVariable("type") String type, @RequestParam(value = "tenantId", required = false) String tenantId) {
        QueryWrapper<Dic> queryWrapper = new QueryWrapper<Dic>();
        queryWrapper.eq("parentType", type);
        if (!StringUtils.isEmpty(tenantId)) {
            queryWrapper.eq("tenantId", tenantId);
        }
        List<Dic> list = dicMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }


    @ApiOperation(value = "获取系统配置", notes = "")
    @GetMapping("/select/systemConfig/{key}")
    public Result<String> getSystemConfig(@PathVariable("key") String key) {
        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sysKey", key);
        List<SystemConfig> list = systemConfigMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list.get(0).getSysValue());
    }


    @ApiOperation(value = "获取系统配置", notes = "")
    @GetMapping("/select/getDiskInfo")
    public Result<Map<String, String>> getDiskInfo() {

        Map<String, String> result = new HashMap<>();
        long totalSpace = 0l;
        long freeSpace = 0l;
        long usedSpace = totalSpace - freeSpace;

        //存储模式
        String accType = RedisUtil.getSysConfig(SystemConfigType.ACCESSORY_TYPE);
        if (!StringUtils.isEmpty(accType)) {
            if (accType.equals(AccessoryType.TYPE_2.getKey())) {
                try{

//                    String ossIp = com.daxt.model.constant.SystemConfig.ossIp;
                    String ossIp = endpoint;
                    String minioConsole = ossIp;
                    //控制台方式获取信息
                    String isWindows = System.getProperty("os.name");
                    if(!StringUtils.isEmpty(isWindows)&&isWindows.contains("Windows")){
                        minioConsole = ossIp;
                    }else {
                        if(ossIp.indexOf("9000")>0){
                            minioConsole = ossIp.replace("9000","9001");
                        }else if(ossIp.indexOf("9001")>0){
                            minioConsole = ossIp.replace("9001","9000");
                        }
                    }
                    HttpDto dto = new HttpDto();
                    dto.setUrl(minioConsole + "/api/v1/login");
                    dto.setParams("{\"accessKey\":\""+accessKey+"\",\"secretKey\":\""+secretKey+"\"}");
//                    dto.setParams("{\"accessKey\":\"minioadmin\",\"secretKey\":\"minioadmin\"}");
                    dto.setParamsMimeType("text/json");

                    Map<String, String> hMap = new HashMap<>();
                    hMap.put("Content-Type", "application/json;charset=UTF-8");
                    dto.setHeaderMap(hMap);
                    //登录minio
                    HttpDto resultDto = HttpClientUtil.basePost(dto);
                    Header[] rHeader = resultDto.getResultHeaders();
                    for (Header h : rHeader) {
                        if (h.getName().equals("Set-Cookie")) {
                            Map<String, String> m = new HashMap();
                            m.put("Cookie", h.getValue());
                            dto.setHeaderMap(m);
                        }
                    }

                    dto.setUrl(minioConsole + "/api/v1/admin/info");
                    //获取存储信息info
                    HttpDto resDto = HttpClientUtil.baseGet(dto);
                    String res = resDto.getResult();
                    System.out.println("res:"+res);
                    JSONObject jo = JSONObject.parseObject(res);
                    List<Map> servers = (List<Map>) jo.get("servers");
                    if(BaseUtil.listIsNotNullElement(servers)){
                        Map serversMap = servers.get(0);
                        List<Map> drivesList = (List<Map>) serversMap.get("drives");
                        Map drives = drivesList.get(0);
                        usedSpace = Long.parseLong(drives.get("usedSpace").toString());
                        freeSpace = Long.parseLong(drives.get("availableSpace").toString());
                        totalSpace = Long.parseLong(drives.get("totalSpace").toString());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    System.err.println("获取桶存储信息失败");
                }

            }
        } else {

            String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
            File file = new File(ossDir);
            totalSpace = file.getTotalSpace();
            freeSpace = file.getFreeSpace();
            usedSpace = totalSpace - freeSpace;

        }

        System.out.println("总空间大小 : " + totalSpace / 1024 / 1024 / 1024 + "G");
        System.out.println("剩余空间大小 : " + freeSpace / 1024 / 1024 / 1024 + "G");
        System.out.println("已用空间大小 : " + usedSpace / 1024 / 1024 / 1024 + "G");

        result.put("totalSpace", totalSpace / 1024 / 1024 / 1024 + "G");
        result.put("freeSpace", freeSpace / 1024 / 1024 / 1024 + "G");
        result.put("usedSpace", usedSpace / 1024 / 1024 / 1024 + "G");


        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, result);

        //获取文件存储信息

    }


    @ApiOperation(value = "获取年度", notes = "")
    @GetMapping("/select/archivalYear/{fondsId}/{typeId}")
    public Result<List<String>> getArchivalYear(@PathVariable("fondsId") String fondsId, @PathVariable("typeId") String typeId) {
        QueryWrapper<ArchivesDoc> queryWrapperYear = new QueryWrapper<ArchivesDoc>();
        queryWrapperYear.eq("fondsId", fondsId);
        if (!StringUtils.isEmpty(typeId) && !"0".equals(typeId))
            queryWrapperYear.eq("typeId", typeId);
        queryWrapperYear.ne("archivalYear","");
        queryWrapperYear.orderByDesc("archivalYear");
        queryWrapperYear.groupBy("archivalYear");
        //queryWrapperYear.select("id", "archivalYear");
        queryWrapperYear.select("archivalYear");


        List<ArchivesDoc> yearList = archivesDocMapper.selectList(queryWrapperYear);
        List<String> result = new ArrayList<String>();
        for (ArchivesDoc doc : yearList) {
            if (doc.getArchivalYear() != null)
                result.add(doc.getArchivalYear());
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, result);
    }


    @ApiOperation(value = "档案统计", notes = "")
    @GetMapping("/select/archives/statistics")
    public Result<ArchivesStatisticsDto> fileDown(
            HttpServletRequest request) {
        Integer fonds = archivesFondsMapper.selectCount(null);
        Integer types = archivesTypeMapper.selectCount(null);
        QueryWrapper<ArchivesDoc> queryWrapper = new QueryWrapper<ArchivesDoc>();
        queryWrapper.eq("fileType", "doc");
        queryWrapper.eq("isDelete", "0");
        queryWrapper.in("state", new String[]{"2", "3"});
        queryWrapper.select("id");
        Integer docCount = archivesDocMapper.selectCount(queryWrapper);
        QueryWrapper<ArchivesDoc> queryWrapper1 = new QueryWrapper<ArchivesDoc>();
        queryWrapper1.eq("fileType", "dossier");
        queryWrapper1.eq("isDelete", "0");
        queryWrapper1.in("state", new String[]{"2", "3"});
        queryWrapper1.select("id");
        Integer dossierCount = archivesDocMapper.selectCount(queryWrapper1);
        Integer fileCount = archivesDocFileMapper.queryFileCount();
        ArchivesStatisticsDto archivesStatistics = new ArchivesStatisticsDto();
        archivesStatistics.setFonds(fonds == null ? 0 : fonds);
        archivesStatistics.setTypes(types == null ? 0 : types);
        archivesStatistics.setDocCount(docCount == null ? 0 : docCount);
        archivesStatistics.setDossierCount(dossierCount == null ? 0 : dossierCount);
        archivesStatistics.setFileCount(fileCount == null ? 0 : fileCount);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", archivesStatistics);
    }
}

